package wbsocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDate;
import java.time.LocalDateTime;

public class MyTextWebSocketFramHander extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        System.out.println("收到服务器消息：" + textWebSocketFrame.text());
        //回复
        channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("用户" + channelHandlerContext.channel().id().asLongText() +"\n"+
                "时间" + LocalDateTime.now() + "说" + textWebSocketFrame.text()));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerAdded 被调用 id:" + ctx.channel().id().asLongText());//唯一id
        System.out.println("handlerAdded 被调用 id:" + ctx.channel().id().asShortText());//非唯一id
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerRemoved 被调用 id:" + ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常发生" + cause.getMessage());
        ctx.close();
    }
}
